﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMusicStore.Models;
using MvcMusicStore.ViewModels;
using Repositories.Models;

namespace MvcMusicStore.Controllers
{
    public class ShoppingCartController : Controller
    {
        //private MusicStoreEntities storeDB = new MusicStoreEntities();
        //// GET: /ShoppingCart/

        public ActionResult Index()
        {
            var cart = ShoppingCart.GetCart(this);
            var viewModel = new ShoppingCartViewModel()
            {
                CartItems = cart.CartItems.ToList(),
                CartTotal = ShoppingCart.GetTotal(cart.CartId)
            };
            return View(viewModel);
        }

        public ActionResult AddToCart(int id)
        {
            var cart = ShoppingCart.GetCart(this);
            var addedAlbum = RepositoryProvider.AlbumRepository.GetById(id);
            if (addedAlbum != null)
            {
                ShoppingCart.AddToCart(cart.CartId, id);
            }
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        {
            var cart = ShoppingCart.GetCart(this);
            var albumRemove = RepositoryProvider.AlbumRepository.GetById(id);
            string albumName = albumRemove.Title;
            //int itemCount = RepositoryProvider.ShoppingCartRepository.Delete(cart.CartId);
            var results = new ShoppingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(albumName) + " has been removed from your shopping cart.",
                CartTotal = ShoppingCart.GetTotal(cart.CartId),
                CartCount = ShoppingCart.GetCount(cart.CartId),
                //ItemCount = itemCount,
                DeleteId = id
            };

            return Json(results);
        }

        [ChildActionOnly]
        public ActionResult CartSummary()
        {
            var cart = ShoppingCart.GetCart(this);
            ViewData["CartCount"] = ShoppingCart.GetCount(cart.CartId);
            return PartialView("CartSummary");
        }
    }
}
